my $nfs_server = fetch_val('nfs_server')
    or return;

my $ports = "all,all:udp";

if (1) # redhat specific
{
    my %conf = (
	LOCKD_UDPPORT => 4045,
	LOCKD_TCPPORT => 4045,
	MOUNTD_PORT   => 4056,
	STATD_PORT    => 4048,
	RQUOTAD_PORT  => 4049,
    );

    my $conf = join("", map "$_=$conf{$_}\n", sort keys %conf);
    my $conf_re = join "|", map quotemeta, sort keys %conf;

    file_append '/etc/sysconfig/nfs', $conf, qr/^(?:$conf_re)=/,
	-create => 1, -reload => "portmap,nfslock,nfs";

    $ports = [ map +($_, "$_:udp"), 111, 2049, sort values %conf ];

    package_install('portmap', 'nfs-utils');
}

my %clients;

$clients{$_} = 1 foreach fetchall_array('nfs_clients');

unless ($nfs_server eq 'manual')
{	       
    my %exports;
    
    foreach my $nfs_export (fetch_all('nfs_export'))
    {
	while (my ($dir, $export) = each %{ $nfs_export })
	{
	    $exports{$dir}{$_} = [ comma_or_arrayref $export->{$_} ]
		foreach keys %$export;
		
	    $clients{$_}++
		foreach map +(ref) ? @$_ : $_, values %$export;
	}
    }       
		
    foreach my $host (type_list('nfs_mount'))
    {
	foreach my $conf (Rollout::fetch_all(\%m, $host, 'nfs_mount'))
	{
	    $conf = $conf->{$hostname}
		or next;
    
	    $clients{$host}++;

	    push @{ $exports{$_}{write} }, $host
		foreach ref $conf eq 'HASH' ? keys %$conf : comma_or_arrayref $conf;
	}   
    }	   
	
    my $export_conf = '';

    foreach my $dir (sort { length $a <=> length $b || $a cmp $b } keys %exports)
    {   
	my @exports;

	foreach my $type (qw/read write/)
	{
	    push @exports, "$_($type)"
		foreach @{ $exports{$dir}{$type}||[] };
	}

	next unless @exports;

	$export_conf .= "$dir\t@exports\n";
    }

    $export_conf =~ s/\(read\)/(ro)/g;
    $export_conf =~ s/\(write\)/(rw,no_root_squash,async)/g;

    text_install "/etc/exports", $export_conf, -run => "exportfs -a";
}

add_class "NFS_server_$hostname" => {
    services => {
	portmap => 1,
	nfslock => 1,
	nfs => 1,
    },
    firewall_input_allow => {
	map +($_ => $ports), keys %clients,
    },
};

1;
